package com.hello.json;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.convert.ConversionService;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;

@Component
public class JacksonConversionServiceConfigurer implements BeanPostProcessor {
	
	private final ConversionService conversionService;
	
	@Autowired
	public JacksonConversionServiceConfigurer(ConversionService conversionService) {
		this.conversionService = conversionService;
	}

	@Override
	public Object postProcessAfterInitialization(Object arg0, String arg1)
			throws BeansException {
		// TODO Auto-generated method stub
		if(arg0 instanceof AnnotationMethodHandlerAdapter) {
			AnnotationMethodHandlerAdapter adapter = (AnnotationMethodHandlerAdapter) arg0;
			HttpMessageConverter<?>[] converters = adapter.getMessageConverters();
			for(HttpMessageConverter<?> converter : converters) {
				if(converter instanceof MappingJacksonHttpMessageConverter) {
					MappingJacksonHttpMessageConverter jsonConverter = (MappingJacksonHttpMessageConverter) converter;
					jsonConverter.setObjectMapper(new ConversionServiceAwareObjectMapper(this.conversionService));
				}
			}
		}
		return arg0;
	}

	@Override
	public Object postProcessBeforeInitialization(Object arg0, String arg1)
			throws BeansException {
		// TODO Auto-generated method stub
		return arg0;
	}

}
